#!/usr/bin/env python
# -*- coding:utf-8 -*-

import urllib2
import threading
import re


class TestProxy(object):
    def __init__(self):
        self.url = 'www.baidu.cn'
        self.proxy_file = 'proxy.txt'
        self.usable_proxy_file = 'usable_proxy.txt'
        self.threads = 1
        self.timeout = 3
        self.regex = re.compile(r'baidu.com')
        self.alive_list = []


    def run(self):
        with open(self.proxy_file, 'r') as fp:
            lines = fp.readlines()
            line = lines.pop()
            while lines:
                # for i in xrange(self.threads):
                #     t = threading.Thread(target=self.link_with_proxy,
                #     args=(line, ))
                #     t.start()
                #
                #     if lines:
                #         line = lines.pop()
                #     else:
                #         continue
                self.link_with_proxy(line)
                line = lines.pop()

        with open(self.usable_proxy_file, 'w') as fp:
            for i in xrange(len(self.alive_list)):
                fp.write(self.alive_list[i])


    def link_with_proxy(self, line):
        # print line
        line_list = line.split('\t')
        # print line_list
        ip = line_list[0]
        port = line_list[1]
        protocol = line_list[3].strip()
        server = protocol + ':\\\\' + ip + ':' + port
        # print server
        opener = urllib2.build_opener(urllib2.ProxyHandler({protocol:server}))
        urllib2.install_opener(opener)

        try:
            response = urllib2.open(url=self.url, timeout=self.timeout)
        except:
            print '%s connect failed' % server
            return
        else:
            try:
                str = response.read()
            except:
                print '%s connect failed' % server
                return
            if self.regex.search(str):
                print '%s connect success' % server
                self.alive_list.append(line)

if __name__ == '__main__':
    TP = TestProxy()
    TP.run()
